package com.uyaer.magic.levels
{
	import com.uyaer.magic.common.Common;
	import com.uyaer.magic.events.EventManager;
	import com.uyaer.magic.events.EventType;
	import com.uyaer.magic.nape.BodyManager;
	
	import nape.phys.Body;
	import nape.phys.BodyType;
	import nape.shape.Circle;
	import nape.shape.Polygon;
	import nape.shape.Shape;

	public class LevelManager
	{
		private var m_chapter:int = 1;
		private var m_level:int = 1;
		
		
		private static var m_instance:LevelManager;
		public function LevelManager()
		{
		}
		
		public static function get i():LevelManager{
			return m_instance ||= new LevelManager();
		}
		
		/**
		 *下一关 
		 */		
		public function next():void{
			this.m_level ++;
			
			initLevel();
		}
		
		/**
		 *重置当前关 
		 */		
		public function reset():void{
			this.initLevel();
		}
		
		/**
		 *选择关卡 
		 * @param chapter
		 * @param level
		 * 
		 */		
		public function select(chapter:int,level:int):void{
			this.m_chapter = chapter;
			this.m_level = level;
			
			initLevel();
		}
		
		private function initLevel():void{
			this.clearAll();
			
			var arr:Array =  LevelData["LEVEL_"+m_chapter+"_"+m_level].shapes;
			var body:Body;
			for each (var bd:Object in arr){
				body = new Body(bd["bodytype"]=="static"?BodyType.STATIC:BodyType.DYNAMIC);
				var shape:Shape;
				if(bd.type == "circle"){
					shape = new Circle(bd.w*0.5);
				}else{
					shape = new Polygon(Polygon.box(bd.w,bd.h));
				}
				body.shapes.add(shape);
				body.position.setxy(bd.x,bd.y);
				body.space = Common.space;
				if(bd.nameid == "ball"){
					BodyManager.i.ball = body;
				}
			}
		}
		
		private function clearAll():void{
			Common.space.bodies.clear();
			EventManager.dispatchEvent(EventType.GAME_RESET);
		}
	}
}